package org.boticelli.controller;

import java.util.Map;

import org.boticelli.Bot;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public abstract class AbstractBotController implements ApplicationContextAware
{

    private ApplicationContext applicationContext;
    private Map<String, Bot> bots;

    /**
     * Finds the bot with the given name.
     * 
     * @param botName
     *            bot name. if <code>null</code>, the only defined bot is
     *            returned
     * @return
     * @throws IllegalArgumentException
     *             if the bot can't be found
     * @throws IllegalArgumentException
     *             if there is no bots are defined
     * @throws IllegalArgumentException
     *             if there's more than one bot defined but no bot name given.
     */
    protected Bot findBot(String botName) throws IllegalArgumentException
    {
        Bot bot = null;
        if (botName == null)
        {
            if (bots == null || bots.size() == 0)
            {
                throw new IllegalArgumentException("No bots defined");
            }
    
            if (bots.size() > 1)
            {
                throw new IllegalArgumentException(
                        "More than one bot defined and no bot name given.");
            }
            // get only bot
            bot = bots.values().iterator().next();
        }
        else
        {
            bot = bots.get(botName);
            if (bot == null)
            {
                throw new IllegalArgumentException("Bot " + botName + " not found");
            }
        }
        return bot;
    }

    /**
     * {@inheritDoc}
     */
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException
    {
        this.applicationContext = applicationContext;

        ApplicationContext ctxt = applicationContext;
        ApplicationContext parent = null;
        while ((parent = ctxt.getParent()) != null)
        {
            ctxt = parent;
        }
    
        this.bots = ctxt.getBeansOfType(Bot.class);
    }

}
